﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Synthetic.MicroApps.Loader;
using Synthetic.MicroApps.Framework;
using System.IO;

namespace Synthetic.MicroApps.Loader.GUI
{
    public partial class LoaderGUI : Form
    {
        private List<IMAFramework> Plugins = new List<IMAFramework>(255);
        public LoaderGUI()
        {
            InitializeComponent();
        }

        private void Loaded(object sender, EventArgs e)
        {
            try
            {
                Plugins.AddRange(Loader.GetPlugins(Application.StartupPath + "\\apps"));
                foreach (IMAFramework app in Plugins)
                {
                    AppBox.Items.Add(app.Name);
                }
            }
            catch
            {
                if (Directory.Exists(Application.StartupPath + "\\apps") == false)
                {
                    DialogResult r = MessageBox.Show(this, "Apps Directory does not exist\nWould you like me to create it now?", "MicroApp Loader", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                    if (r == System.Windows.Forms.DialogResult.Yes)
                    {
                        Directory.CreateDirectory(Application.StartupPath + "\\apps");
                    }
                }
            }
        }

        private void AppBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateUserView(AppBox.SelectedIndex);
        }

        private void UpdateUserView(int index)
        {
            try
            {
                appName.Text = Plugins[index].Name;
                appDescription.Text = Plugins[index].Description;
                appAuthor.Text = Plugins[index].Author;
                appURL.Text = Plugins[index].AuthorURL;
            }
            catch
            {
                try
                {
                    appName.Text = Plugins[index].Name;
                    appDescription.Text = Plugins[index].Description;
                    appAuthor.Text = Plugins[index].Author;
                    appURL.Text = Plugins[index].AuthorURL;
                }
                catch
                {
                    MessageBox.Show(this, "Error Loading Application Data!", "MicroApp Loader", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void ExecuteApp(int index)
        {
            Plugins[index].Action();
        }

        private void openApp_Click(object sender, EventArgs e)
        {
            ExecuteApp(AppBox.SelectedIndex);
        }
    }
}
